//
//  LabelViewController.m
//  eBook
//
//  Created by zhy on 12-12-2.
//  Copyright (c) 2012年 zhan. All rights reserved.
//

#import "LabelViewController.h"
#import "AppDelegate.h"
@interface LabelViewController ()

@end

@implementation LabelViewController
@synthesize LabelVCDelegate;
@synthesize labelTableView;
@synthesize AddBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"viewdidload");
    
    AllLabelArray = [[NSMutableArray alloc] init];
    
    labelTableView.delegate = self;
    labelTableView.dataSource = self;
    
    
    currentRow = -1;
    
    [self loadDataFromCoreData]; // popover: viewdidload before prepareForSegue . so ,i put it to prepareforsegue 

}

- (void)viewDidUnload
{
    [self setLabelTableView:nil];
    [self setAddBtn:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

#pragma mark - private Method

-(void) loadDataFromCoreData{
    NSLog(@"loadDataFromCoreData and chapter page are %d,%d",currentChapter,currentPage);
    
    AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Label"
                                              inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    
    if (objects == nil) {
        NSLog(@"there was a error!");
    }
    
    [AllLabelArray removeAllObjects];
    
    int i = 0;
    for (NSManagedObject *oneObject in objects) {
        
        NSNumber *chapter = [oneObject valueForKey:@"chapter"];
        NSNumber *feature = [oneObject valueForKey:@"feature"];
        NSNumber *page = [oneObject valueForKey:@"page"];
        NSString *imageURL = [oneObject valueForKey:@"imageURL"];
        NSDictionary *onedata = [[NSDictionary alloc] initWithObjectsAndKeys:chapter,@"chapter",feature,@"feature",page,@"page",imageURL,@"imageURL",nil];

        [AllLabelArray addObject:onedata];
        
        if (([chapter intValue] == currentChapter)&&([page intValue] == currentPage)){
            currentRow = i;
            
            [AddBtn setTitle:@"移除书签" forState:UIControlStateNormal];
//            [AddBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            NSLog(@"haha");
        }
        i=i+1;
    }
    
}

-(void) deleteDatafCoreDatawithIndex:(int) index{
    
    AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Label"
                                              inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    [context deleteObject:[objects objectAtIndex:index]];
    [appDelegate saveContext];
}


-(void) setChapter:(int)chapter andFeature:(int)feature andPage:(int)page{
    NSLog(@"setCCCCPPPP %d,%d",chapter,page);
    currentChapter = chapter;
    currentFeature = feature;
    currentPage = page;
}

#pragma mark - Action
- (IBAction)AddORDeleteLabelAction:(id)sender {

    // -1:表示当前页不知当前列表书签中, >=0 ：表示已经当前页面已经加入列表的位置
    NSLog(@"button action and current row is %d ",currentRow);
    if (currentRow == -1) {
        
        [LabelVCDelegate AddLabel];
        [self loadDataFromCoreData];
        [labelTableView reloadData];
        
        [AddBtn setTitle:@"移除书签" forState:UIControlStateNormal];
//        [AddBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    } else {
    
        [AllLabelArray removeObjectAtIndex:currentRow];
        [self deleteDatafCoreDatawithIndex:currentRow];
        
        [labelTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:currentRow inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        
        currentRow = -1;
        
        [AddBtn setTitle:@"添加书签" forState:UIControlStateNormal];
        [AddBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    
}

#pragma mark - tableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    currentRow = indexPath.row;
    [AddBtn setTitle:@"移除书签" forState:UIControlStateNormal];
//    [AddBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    
    
    NSNumber *chapter = [[AllLabelArray objectAtIndex:indexPath.row] valueForKey:@"chapter"];
    NSNumber *feature = [[AllLabelArray objectAtIndex:indexPath.row] valueForKey:@"feature"];
    NSNumber *page = [[AllLabelArray objectAtIndex:indexPath.row] valueForKey:@"page"];
    
    int c = [chapter intValue];
    int f = [feature intValue];
    int p = [page intValue];
    
    if (c == currentChapter && f == currentFeature) {
        [LabelVCDelegate LabelSelectedWithPage:p];
    } else {
        [LabelVCDelegate LabelSelectedwithChapter:c andFeature:f andPage:p];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [AllLabelArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"labelTableviewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    NSString *path = [[AllLabelArray objectAtIndex:indexPath.row] valueForKey:@"imageURL"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    UIImage *image = [UIImage imageWithData:data];
    cell.imageView.image = image;
    
    
    NSNumber *chapter = [[AllLabelArray objectAtIndex:indexPath.row] valueForKey:@"chapter"];
    NSNumber *feature = [[AllLabelArray objectAtIndex:indexPath.row] valueForKey:@"feature"];
    NSNumber *page = [[AllLabelArray objectAtIndex:indexPath.row] valueForKey:@"page"];
    
    int c = [chapter intValue];
    int p = [page intValue];
    int f = [feature intValue];
    NSString *str = [NSString stringWithFormat:@"第%d章专题%d第%d页",c,f,p];
    cell.textLabel.text = str;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    
    return cell;
}
-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [AllLabelArray removeObjectAtIndex:indexPath.row];
        [self deleteDatafCoreDatawithIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
       
        if (indexPath.row == currentRow) {
            [AddBtn setTitle:@"添加书签" forState:UIControlStateNormal];
            [AddBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            currentRow = -1;
        }
        
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

@end
